package com.ophiux.cs.api.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ophiux.cs.application.core.AppResultCode;
import com.ophiux.cs.application.core.Request;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.application.core.ResultEnum;
import com.ophiux.cs.domain.sign.domainservice.SignDomainService;
import com.ophiux.utils.common.StringUtil;
import com.ophiux.utils.parser.json.JsonUtils;

//@Aspect
//@Component
public class CheckSignAspect {
	final static Logger logger = LoggerFactory.getLogger(CheckSignAspect.class);

	ThreadLocal<Long> beginTime = new ThreadLocal<Long>();
	@Autowired
	SignDomainService signDomainService;
	
	//json转换
	protected static JsonUtils json = JsonUtils.getIstance();

	@Pointcut("@annotation(checkSign)")
	public void serviceStatistics(CheckSign checkSign) {
	}

	@Around("serviceStatistics(checkSign)")
	public String doBefore(ProceedingJoinPoint joinPoint, CheckSign checkSign) {
		// 记录请求到达时间
		beginTime.set(System.currentTimeMillis());
		/**
		 * Signature 包含了方法名、申明类型以及地址等信息
		 */
		String class_name = joinPoint.getTarget().getClass().getName();
		String method_name = joinPoint.getSignature().getName();
		
		
		String result = null;
		Object[] method_args = joinPoint.getArgs();
		logger.info("类名"+class_name+",方法"+method_name+",验证签名。参数为："+method_args[0]+"");
		try {
            try {
            	/**
            	 * 获取方法的参数值数组
            	 */
            	String paramNames = method_args[0]+"";
//            	logger.info("请求参数:"+paramNames);
            	
            	/**
            	 * 1.对参数进行签名验证
            	 * 2.判断签名是否正确，如果正确，执行后面的操作，如果不正确，则直接返回
            	 * 3.如果正确，执行后面的操作后，响应参数进行签名
            	 */
//            	paramNames
            	Request req = json.toEntity(paramNames, Request.class);
            	if(req.getHEAD() == null || StringUtil.isEmpty(req.getHEAD().getSIGN())) {
            		logger.info(method_name+"--->请求参数不合法");
            		Result signResult =	Result.fail(ResultEnum.requestParamFail.getCode(),ResultEnum.requestParamFail.getMsg());
    				String sign = signDomainService.getSign("");//默认系统唯一密钥
	               	signResult.setSIGN(sign);
	               	result = json.toJson(signResult);
            	}else {
            		boolean signPd = signDomainService.verSign(req.getHEAD().getSIGN());
            		if(signPd) {//签名验证通过
            			
            			//执行业务方法
    	               	result = (String) joinPoint.proceed();
    	               	
//    	               	result
    	               	Result signResult =	json.toEntity(result, Result.class);
    	               	
    	               	String sign = signDomainService.getSign("");//默认系统唯一密钥
    	               	signResult.setSIGN(sign);
    	               	
    	               	result = json.toJson(signResult);
            		}else {//签名验证未通过 
            			logger.info(method_name+"--->签名不合法");
        				result = json.toJson(Result.fail(ResultEnum.SignFail.getCode(),ResultEnum.SignFail.getMsg()));
            		}
            	}
            	logger.info(method_name+"--->响应参数："+result);
			} catch (Throwable e) {
				e.printStackTrace();
				logger.info("验证签名异常1",e);
				result = json.toJson(Result.fail(AppResultCode.EXCEPTION,"验证签名错误"));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("验证签名异常2",e);
			result = json.toJson(Result.fail(AppResultCode.EXCEPTION,"验证签名错误"));
		}
		
		return result;
	}

}
